<?php
/**
 * Created by PhpStorm.
 * User: tengwei
 * Date: 2018/11/16
 * Time: 10:06 AM
 */

namespace common\logics\bank;

use common\widgets\Request;
use common\widgets\Tool;
use yii\base\BaseObject;
use Yii;

class BankLogic extends BaseObject implements IBank
{
    /** @var \common\sources\read\bank\BankAccess $RBankAccess */
    private $RBankAccess;
    /** @var \common\sources\write\bank\BankAccess $RBankAccess */
    private $WBankAccess;
    /** @var \common\sources\read\buyuser\BuyUserAccess $RBuyUserAccess */
    private $RBuyUserAccess;
    /** @var  \common\sources\read\message\MesgAccess  $RMesgAccess */
    private $RMesgAccess;
    /** @var \common\sources\write\message\MesgAccess  $WMesgAcdess */
    private $WMesgAcdess;


    public function init()
    {
        $this->RBankAccess = Yii::$container->get('RBankAccess');
        $this->WBankAccess = Yii::$container->get('WBankAccess');
        $this->RBuyUserAccess = Yii::$container->get('RBuyUserAccess');
        $this->RMesgAccess = Yii::$container->get('RMesgAccess');
        $this->WMesgAcdess = Yii::$container->get('WMesgAccess');
        parent::init();
    }

    public function addBdBank($param)
    {
        if (empty($param['buy_id'])){
            return Tool::returnJson([],401,'买手id不能为空');
        }
        if (empty($param['real_name'])){
            return Tool::returnJson([],402,'姓名不能为空');
        }
        if (empty($param['cardnum'])){
            return Tool::returnJson([],403,'银行卡号不能为空');
        }
        if (empty($param['bankname'])){
            return Tool::returnJson([],405,'银行名不能为空');
        }
        if(empty($param['pro_name'])){
            return Tool::returnJson([],407,'省名称不能为空');
        }
        if(empty($param['pro_code'])){
            return Tool::returnJson([],408,'省代号不能为空');
        }
        if(empty($param['city_name'])){
            return Tool::returnJson([],409,'市名称不能为空');
        }
        if(empty($param['city_code'])){
            return Tool::returnJson([],410,'市代号不能为空');
        }
        if (empty($param['bankbranch'])){
            return Tool::returnJson([],411,'开户支行名称不能为空');
        }
        if (empty($param['idcard'])){
            return Tool::returnJson([],412,'身份证号不能为空');
        }
        if (empty($param['bankphone'])){
            return Tool::returnJson([],413,'银行预留手机号不能为空');
        }
        if (empty($param['verifycode'])){
            return Tool::returnJson([],415,'验证码不能为空');
        }

        $real_name = $param['real_name'];
        $idcard = $param['idcard'];
        $cardnum = $param['cardnum'];
        $bankphone = $param['bankphone'];
        $param['update_time'] = '';
        $param['create_time'] = time();
        //判断用户是否已经绑定过 如果绑定过  不让用户再次绑定
        $userBank = $this->RBankAccess->getBuyUserBankAccount($param['buy_id']);
        if(!empty($userBank)){
            return Tool::returnJson([],416,'该买手用户已经绑定体现银行卡，不能再次绑定');
        }
        //短信验证码 校验
        $data['phone']=$param['bankphone'];
        $smsArr = $this->RMesgAccess->getVerifyCode($param['bankphone'],5);
        if (intval($smsArr['verifycode']) != (int)$param['verifycode']){
            return Tool::returnJson([],417,'验证码错误');
        }
        //组装四要素数组
        $rescard = $this->cardAuth(['real_name'=> $real_name,"idcard"=>$idcard,"cardnum"=> $cardnum,"bankphone"=> $bankphone]);
        $resarr = json_decode($rescard, true);
        if($resarr['data']['result'] != '01'){
            return Tool::returnJson([],420, $resarr['data']['remark']);
        }
        if(!(strpos($resarr['data']['bankName'],$param['bankname']) !== false)){
            return Tool::returnJson([],419,'选择开户行与卡开户行不匹配');
        }
        $transaction = Yii::$app->db->beginTransaction();
        try{
            if ($resarr['data']['result'] == '01') {
                $result = $this->WBankAccess->addBdBank($param);
                if(!$result){
                    $transaction->rollBack();
                    return Tool::returnJson([],420,'银行卡信息存储失败');
                }
                $this->WMesgAcdess->modifyCodeStatus($smsArr['id']);
                $transaction->commit();
                return Tool::returnJson([],200,'绑定银行卡成功');
            }
            $transaction->rollBack();
            return Tool::returnJson([],421,'你输入的银行信息有误,请重新输入, 错误如：'.$resarr['data']['remark']);
        }catch (\Exception $e){
            $transaction->rollBack();
            return Tool::returnJson([],422,'绑定银行卡失败'.$e->getMessage());
        };
    }

    //获取提现列表
    public function getReflectList($param)
    {
        if (empty($param['buy_id'])){
            return Tool::returnJson([],401,'买手id不能为空');
        }
        //用户
        $buyUser = $this->RBuyUserAccess->getBuyUserInfo($param['buy_id']);
        if(empty($buyUser)){
            return Tool::returnJson([],402,'买手用户不存在');
        }
        //获取绑定银行卡信息
        $buyUserBank = $this->RBankAccess->getBuyUserBankAccount($param['buy_id']);
        $arr = [];
        if(!empty($buyUserBank)){
            $banks = array(
                'real_name' => !empty($buyUserBank['real_name']) ? $buyUserBank['real_name']:'',
                'typename' => !empty($buyUserBank['bankname']) ? $buyUserBank['bankname'] : '',
                'cardnum' => !empty($buyUserBank['cardnum']) ? $buyUserBank['cardnum'] : '',
                'status' => isset(Yii::$app->params['audit_status'][$buyUserBank['status']]) ? Yii::$app->params['audit_status'][$buyUserBank['status']]:'',
            );
            $ids = array(
                'real_name' => $buyUserBank['real_name'],
                'typename' => '身份证',
                'cardnum' => $buyUserBank['idcard'],
                'status' => Yii::$app->params['audit_status'][$buyUserBank['status']],
                "id_positive_url" =>$buyUserBank['id_positive_url'],
                "id_verso_url" => $buyUserBank['id_verso_url'],
            );
            $arr[0] = $banks;
            $arr[1] = $ids;
        }
        return Tool::returnJson($arr, 200);
    }

    public function getBankDetail($param)
    {
        if(empty($param['bus_id']))
        {
            return Tool::returnJson([],401,'商家id不能为空');
        }
        if(empty($param['safetyCode']))
        {
            return Tool::returnJson([],402,'安全码不能为空');
        }
        if(md5($param['bus_id']) != $param['safetyCode'])
        {
            return Tool::returnJson([],403,'安全码不正确');
        }
        $bank = $this->RBankAccess->getBuyUserBankAccount($param['bus_id']);
        if(empty($bank))
        {
            return Tool::returnJson([],403,'绑定账号不存在');
        }
        if($bank['buy_id'] != $param['bus_id'])
        {
            return Tool::returnJson([],405,'非本用户绑定信息');
        }
        $bank['AliPay'] = isset($bank['AliPay']) ? $bank['AliPay'] : '';
        $bank['aliUrl'] = isset($bank['aliUrl']) ? $bank['aliUrl'] : '';
        $bank['bankCardUrl'] = isset($bank['bankCardUrl']) ? $bank['bankCardUrl'] : '';
        $bank['idCardUrl'] = isset($bank['idCardUrl']) ? $bank['idCardUrl'] : '';
        $bank['id_positive_url'] = isset($bank['id_positive_url']) ? $bank['id_positive_url'] : '';
        $bank['id_verso_url'] = isset($bank['id_verso_url']) ? $bank['id_verso_url'] : '';
        return Tool::returnJson($bank,200,"成功");
    }

    public function modifyBank($param)
    {
        if(empty($param['b_id'])){
            return Tool::returnJson([],401,'提现绑定id不能为空');
        }
        if(empty($param['real_name'])){
            return Tool::returnJson([],402,'真实姓名不能为空');
        }
        if (empty($param['cardnum'])){
            return Tool::returnJson([],403,'银行卡号不能为空');
        }
        if(empty($param['bankname'])){
            return Tool::returnJson([],405,'银行名称不能为空');
        }
        if(empty($param['pro_name'])){
            return Tool::returnJson([],406,'省名称不能为空');
        }
        if(empty($param['pro_code'])){
            return Tool::returnJson([],407,'省代号不能为空');
        }
        if(empty($param['city_name'])){
            return Tool::returnJson([],408,'市名称不能为空');
        }
        if(empty($param['city_code'])){
            return Tool::returnJson([],409,'市代号不能为空');
        }
        if (empty($param['bankbranch'])){
            return Tool::returnJson([],410,'开户支行名称不能为空');
        }
        if(empty($param['idcard'])){
            return Tool::returnJson([],411,'身份证号不能为空');
        }
        if (empty($param['bankphone'])){
            return Tool::returnJson([],412,'银行预留手机号不能为空');
        }
        if (empty($param['verifycode'])){
            return Tool::returnJson([],413,'验证码不能为空');
        }
        //判断该提现绑定是否绑定
        $buyUserBank = $this->RBankAccess->getBuyUserBankById($param['b_id']);
        if(empty($buyUserBank)){
            return Tool::returnJson([],415,'该提现绑定不存在,请重新输入');
        }
        //短信验证码 校验
        $data['phone']=$param['bankphone'];
        $smsArr = $this->RMesgAccess->getVerifyCode($param['bankphone'],5);
        if (intval($smsArr['verifycode']) !== intval($param['verifycode'])){
            return Tool::returnJson([],416,'验证码错误');
        }

        $real_name = $param['real_name'];
        $idcard = $param['idcard'];
        $cardnum = $param['cardnum'];
        $bankphone = $param['bankphone'];
        $param['update_time'] = time();

        //组装四要素数组
        $data = compact('real_name','idcard','cardnum','bankphone');
        $rescard = $this->cardAuth($data);
        $resarr = json_decode($rescard, true);

        if($resarr['code'] != 200000){
            return Tool::returnJson([],418, $resarr['message']);
        }
        if(!(strpos($resarr['data']['bankName'],$param['bankname']) !== false)){
            return Tool::returnJson([],419,'选择开户行与卡开户行不匹配');
        }
        $transaction = Yii::$app->db->beginTransaction();
        try{

            if ($resarr['data']['result'] == '01') {
                $result = $this->WBankAccess->modifyBank($param);
                if(!$result){
                    $transaction->rollBack();
                    return Tool::returnJson([],420,'银行卡信息存储失败');
                }
                $this->WMesgAcdess->modifyCodeStatus($smsArr['id']);
                $transaction->commit();
                return Tool::returnJson([],200,'修改成功');
            }
            $transaction->rollBack();
            return Tool::returnJson([],421,'你输入的银行信息有误,请重新输入, 错误如：'.$resarr['data']['remark']);
        }catch (\Exception $e){
            $transaction->rollBack();
            return Tool::returnJson([],523,'修改绑定银行卡失败');
        };
    }

    //检验方法
    private function cardAuth($data)
    {
        $apiId = Yii::$app->params['bank_config']['bank_params']['appId'];
        $appKey = Yii::$app->params['bank_config']['bank_params']['appKey'];
        $params = [
            'appId' => $apiId, // appId,登录万数平台查看
            'appKey' => $appKey, // appKey,登录万数平台查看
            'name' => $data['real_name'], // 姓名
            'idNum' => $data['idcard'], // 身份证号码，限单个
            'cardNo' => $data['cardnum'], // 银行卡号，限单个
            'mobile' => $data['bankphone'], // 银行预留手机号码，限单个，仅支持国内11位号码
            'Content-Type'=>'multipart/form-data',
        ];
        //发送验证
        $result = $this->sendAuth($params);
        return $result;
    }

    private function sendAuth($params)
    {
        $url = Yii::$app->params['bank_config']['bank_url'];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        $result = curl_exec($ch);
        return $result;
    }
}